/**
 * desc: 公用上传图片接口
 * @size {num} require: false 限制图片大小 ，以兆为单位
 * @img {str} require: false 图片url 用来回显示
 * @noRemove {bool} require: false 是否展示删除图标
 * @className {str} require: false 用来设置图片上传框以及上传之后的尺寸大小middle,large,small不传为默认default(84))
 * @handleOk {func} require: true 图片上传完毕之后把图片返回
 */
import React, { useState, useEffect } from 'react';
import { Upload, message } from 'antd';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import { Base64 } from 'js-base64';
import { getToken } from '@/utils/authority';
import CommonLoading from '@/components/CommonLoading';
import CommonModal from '@/components/CommonModal';
import { httpChange } from '@/utils/utils.jsx';
import ImageCompressor from './ImageCompressor';
import ConvertImage from './ConvertImage';
import './index.less';

const clientId = 'sword'; // 客户端id
const clientSecret = 'sword_secret'; // 客户端密钥
const headers = {
  Authorization: `Basic ${Base64.encode(`${clientId}:${clientSecret}`)}`,
  'Blade-Auth': getToken(),
};

const getBase64 = (file) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.onload = () => resolve(reader.result);

    reader.onerror = (error) => reject(error);
  });

const CommonQinnvImgsLoad = (props) => {
  const [imgUrl, setImgUrl] = useState('');
  const [previewVisible, setPreviewVisible] = useState(false);
  const [fileImgList, setFileImgList] = useState([]); //文件列表
  const [loading, setLoading] = useState(false);

  const {
    className,
    img,
    size = 5,
    disabled,
    actionUrl,
    customText,
    customNode,
    handleOk,
    handleFailed,
    noRemove = false,
    onPreview,
  } = props;

  useEffect(() => {
    if (img) {
      setFileImgList([
        {
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: img,
        },
      ]);
    }
  }, [img]);

  const beforeUpload = async (file) => {
    const isLt2M = file.size / 1024 / 1024 < size; //是否大于限制的大小
    const imgSize = file.size / 1024 / 1024;
    if (isLt2M) {
      if (imgSize > 1) {
        let img = file;
        const fileType = file.name.substring(img.name.indexOf('.') + 1);
        // 判断文件是不是jpeg 不是jpeg的都转成jpeg
        if (!['jpeg', 'jpg'].includes(fileType)) {
          img = await ConvertImage(img); //转陈jpeg格式的file
        }
        return await ImageCompressor(img, 'file', 0.6); //图片压缩
      } else {
        return true;
      }
    } else {
      message.error(`图片大小不能超过${size}M!`);
      return isLt2M;
    }
    // const isJpgOrPng =
    //   file.type === 'image/jpeg' ||
    //   file.type === 'image/png' ||
    //   file.type === 'image/jpg';
    // if (!isJpgOrPng) {
    //   message.error('只能上传JPG/JPEG/PNG格式的图片!');
    // }
    // //默认限制尺寸5兆
    // const isLt2M = file.size / 1024 / 1024 < size;
    // if (!isLt2M) {
    //   message.error(`图片大小不能超过${size}M!`);
    // }
    // return isJpgOrPng && isLt2M;
  };

  //点击上传的回调
  const handleChange = async ({ file, fileList }) => {
    if (!file.status) {
      handleFailed();
    }
    if (file.status === 'uploading') {
      setLoading(true);
    }
    if (file.status === 'done') {
      handleOk(file?.response, file?.originFileObj);
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      setImgUrl(file.url || file.preview);
      setLoading(false);
    }
    if (file.status == 'error') {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      setImgUrl(file.url || file.preview);
      setLoading(false);
    }
    if (file.status === 'removed') {
      handleOk(undefined);
    }
    setFileImgList([...fileList]);
  };

  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setImgUrl(file.url || file.preview);
    setPreviewVisible(true);
  };

  //关闭查看上传图片
  const handleCancel = () => {
    setPreviewVisible(false);
  };

  //移除图片
  const handleRemove = () => {
    setLoading(true);
    setImgUrl('');
    setFileImgList([]);
    handleOk();
    setTimeout(() => {
      //处理渲染问题
      setLoading(false);
    }, 300);
  };

  //展示loading状态
  const loadingRender = () => {
    const uploadButton = customNode ? (
      customNode
    ) : (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div style={{ marginTop: 8 }}>{customText || '上传'}</div>
      </div>
    );
    if (imgUrl || fileImgList.length > 0) {
      return null;
    } else {
      return uploadButton;
    }
  };

  return (
    <>
      <Upload
        name="file"
        headers={headers}
        listType="picture-card"
        className={className}
        onPreview={onPreview ? onPreview : handlePreview}
        onRemove={handleRemove}
        action={`${httpChange(UPLOAD_SERVER)}${actionUrl}`}
        beforeUpload={beforeUpload}
        onChange={handleChange}
        disabled={disabled}
        showUploadList={{
          showRemoveIcon: noRemove ? false : true,
        }}
        accept=".jpg,.jpeg,.png"
        fileList={fileImgList}
      >
        {!loading && loadingRender()}
      </Upload>
      <CommonModal
        visible={previewVisible}
        title="图片预览"
        footer={null}
        onCancel={handleCancel}
      >
        <img alt="" style={{ width: '100%' }} src={imgUrl} />
      </CommonModal>
      <CommonLoading loading={loading} />
    </>
  );
};

export default CommonQinnvImgsLoad;
